package com.example.demo.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

@Configuration
public class ElasticSearchConfig {

    @Value("${spring.elasticsearch.username}")
    public String  name;
    @Value("${spring.elasticsearch.password}")
    public String  password;
    @Value("${spring.elasticsearch.uris}")
    private String uris;

    @Bean
    public RestHighLevelClient client() {

        uris = uris.replace("http://", "");
        String[] strings = uris.split(":");
        String hostName = strings[0];
        int port = Integer.parseInt(strings[1]);

        RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(hostName, port));
        if (StringUtils.hasText(name) && StringUtils.hasText(password)) {
            restClientBuilder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(new BasicCredentialsProvider() {
                {
                    setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(name, password));
                }
            }));
        }
        restClientBuilder
            .setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setConnectTimeout(1000 * 60 * 10).setSocketTimeout(1000 * 60 * 10).setConnectionRequestTimeout(1000 * 60 * 10));
        RestHighLevelClient client = new RestHighLevelClient(restClientBuilder);
        return client;
    }

}
